package com.jiangxjsy.authorization.controller;

import cn.hutool.core.util.StrUtil;
import com.jiangxjsy.authorization.service.LoginService;
import com.jiangxjsy.core.constant.BasicConstant;
import com.jiangxjsy.core.wrap.Result;
import com.jiangxjsy.core.wrap.ResultBuilder;
import com.jiangxjsy.core.wrap.ResultCode;
import com.jiangxjsy.model.authorization.entity.AuthorizationUser;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * wukong-crm-master
 * 蒋胜宇
 * 2025/6/3 16:43
 */

@RestController
public class AuthorizationController {
    @Resource
    private LoginService loginService;

    /**
     * 权限校验
     *
     * @param url 请求地址
     * @param method 请求方法
     * @param request 请求
     * @return 结果
     */
    @RequestMapping(value = "/permission")
    public Result<?> permission(@RequestParam("url") String url, @SuppressWarnings("unused") @RequestParam("method") String method, HttpServletRequest request) {
        String token = request.getHeader(BasicConstant.TOKEN_NAME);
        String proxyHost = request.getHeader("proxyHost");
        return loginService.permission(token, url, proxyHost);
    }

    /**
     * 登录
     *
     * @param user 登录用户
     * @param response 响应
     * @param request 请求
     * @return 结果
     */
    @PostMapping(value = "/login")
    public Result<?> login(@RequestBody AuthorizationUser user, HttpServletResponse response, HttpServletRequest request) {
        if (StrUtil.isNotEmpty(user.getUsername())) {
            if (StrUtil.trimToNull(user.getUsername()) == null) {
                return ResultBuilder.error(ResultCode.AuthorizationResultCode.AUTHORIZATION_USERNAME_REQUIRED);
            }
            if (StrUtil.trimToNull(user.getPassword()) == null && StrUtil.trimToNull(user.getSmscode()) == null) {
                return ResultBuilder.error(ResultCode.AuthorizationResultCode.AUTHORIZATION_PASSWORD_REQUIRED);
            }
        }
        return loginService.login(user, response, request);
    }

    /**
     * 注销
     *
     * @param request 请求
     * @param response 响应
     * @return 结果
     */
    @RequestMapping(value = "/logout")
    public Result<?> logout(HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader(BasicConstant.TOKEN_NAME);
        if (StrUtil.isNotEmpty(token)) {
            Result<?> ignore = loginService.logout(token, response, request);
        }
        return ResultBuilder.ok();
    }
}
